package com.lap.generator.domain.template.strategy;

import com.lap.generator.application.assembler.ModelTransformer;
import com.lap.generator.commons.exception.GeneratorException;
import com.lap.generator.commons.tools.FileUtil;
import com.lap.generator.commons.tools.PackageUtil;
import com.lap.generator.domain.CoreFile;
import com.lap.generator.domain.TemplateModel;
import com.lap.generator.domain.template.CodeGenContext;
import com.lap.generator.domain.template.CodeTemplate;
import com.lap.generator.domain.valueobject.CodeType;
import com.lap.generator.infrastructure.persistence.TemplateEngine;
import freemarker.template.TemplateException;
import java.io.IOException;
import java.util.List;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class PersistenceMapperGen implements CodeTemplate<CoreFile> {
  @Override
  public CodeType getType() {
    return CodeType.DRIVING;
  }

  @Override
  public List<CoreFile> generate(CodeGenContext context) {
    TemplateModel model = ModelTransformer.transform(context.tableMeta(), context.envConfig());
    try {
      TemplateEngine engine = new TemplateEngine();
      String persistencePackageName = PackageUtil.pack2Path(model.getBasePackage(), "adapter.driving.persistence",
          model.getModule(), "mapper");
      
      String persistenceContent =
          engine.processTemplate("adapter/driving/PersistenceMapper.java.ftl", model);
      String persistenceFileName = FileUtil.resolverFile("java", model.getClassName(), "Mapper");
      CoreFile persistenceFile =
          CoreFile.builder()
          .path(persistencePackageName)
          .fileName(persistenceFileName)
          .content(persistenceContent)
          .build();

      String xmlContent =
          engine.processTemplate("adapter/driving/PersistenceMapper.xml.ftl", model);
      String xmlFileName = FileUtil.resolverFile("xml", model.getClassName(), "Mapper");
      CoreFile xmlFile =
          CoreFile.builder()
          .path(persistencePackageName)
          .fileName(xmlFileName)
          .content(xmlContent)
          .build();

      return List.of(persistenceFile, xmlFile);
    } catch (IOException | TemplateException e) {
      throw new GeneratorException("Domain engine error:", e);
    }
  }
}
